<?php


namespace app\console\middleware;



use app\console\model\Admin;
use app\console\model\AdminRole;
use think\facade\Db;
use think\facade\Log;
use think\facade\Request;
use think\facade\Route;
use think\facade\Session;
use think\facade\View;
use think\facade\Event;

class Privilege
{
    private $controller;
    private $action;
    public function handle($request, \Closure $next)
    {
        // 添加中间件执行代码
        // 关闭当前日志写入

        $this->controller = $request->controller();

        $this->action = $request->action();
//        Log::info('日志信息{user}', ['user' => '流年']);
        if($this->action == 'index'){

            $ret = session($this->controller.'_url',request()->url()); //当前url
         // session($this->controller.'_url_excel',request()->url()."&list_rows=10000000&page=1");//当前url加网址

           session($this->controller.'_url_excel',url('export',request()->param())->build());//当前url加网址
           Session::save();
        }
        if (Session::has('admin_id') == false) {
            redirect(url('Login/index'));
            //jump('请登录', Route::buildUrl('Login/index'));//会一直请登良
        }

//        $admin_name = Db::name('admin')->where('id', Session::get('admin_id'))->value('admin_name');
//
//        View::assign('admin_name', $admin_name);

        if (!(new Admin())->check_pri()) {
                fail('没有权限');
        }

        //左侧权限列表
        $pri_data = AdminRole::alias('admin_role')
            ->join('role_pri', 'admin_role.role_id = role_pri.role_id', 'LEFT')
            ->join('privilege', 'role_pri.pri_id = privilege.id', 'LEFT')
            ->order(['privilege.sort' => 'asc','privilege.id' => 'asc'])
            ->group('privilege.id')
            ->where('admin_role.admin_id', '=', Session::get('admin_id'))

            ->where('privilege.status', 1)->select();

        $pri_data = getMenuList($pri_data);
        View::assign('pri_data', $pri_data);
        $module = app('http')->getName();


        $url = $module . '/' . $this->controller . '/' . $this->action;
        $code = Db::name('Privilege')->where('url', $url)->value('code');

        $pri_name = Db::name('Privilege')->where('url', $url)->value('pri_name');

        View::assign('code', trim($code));
        View::assign('pri_name', $pri_name);
        View::assign('url', $url);

        // 清空所有日志

        return $next($request);
    }

    public function end(){

    }
}